package org.jeecg.config;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.servlet.Servlet;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.valves.ErrorReportValve;
import org.apache.coyote.UpgradeProtocol;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import  org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import  org.springframework.boot.autoconfigure.web.embedded.TomcatWebServerFactoryCustomizer;
import  org.springframework.boot.web.embedded.tomcat.ConfigurableTomcatWebServerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
/**
 * @author HuFuGui
 * @version 1.0
 * @description
 * @date 2023-06-09 10:25
 */
@Aspect
@ConditionalOnClass({ Servlet.class, Tomcat.class,  UpgradeProtocol.class,  TomcatWebServerFactoryCustomizer.class })
@Component
public class TomcatCustomizerAspect {
    @Pointcut("execution(public void  org.springframework.boot.autoconfigure.web.embedded.TomcatWebServerFactoryCustomizer.customize(*))")
    public void customize() {
    }
    @After(value = "customize()")
    public void doAfter(JoinPoint joinPoint) throws  Throwable {
        if (!(joinPoint.getArgs()[0] instanceof  ConfigurableTomcatWebServerFactory)) {
            return;
        }
        ConfigurableTomcatWebServerFactory factory =  (ConfigurableTomcatWebServerFactory)  joinPoint.getArgs()[0];
        addTomcat404CodePage(factory);
    }
    private static void  addTomcat404CodePage(ConfigurableTomcatWebServerFactory  factory) {
        factory.addContextCustomizers((context) -> {
            String path =  context.getCatalinaBase().getPath() + "/404.html";
            ClassPathResource cr = new  ClassPathResource("404.html");
            if (cr.exists()) {
                File file404 = new File(path);
                if (!file404.exists()) {
                    try {
                        FileCopyUtils.copy(cr.getInputStream(),  new FileOutputStream(file404));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            ErrorReportValve valve = new  ErrorReportValve();
            valve.setProperty("errorCode.404", path);
            valve.setShowServerInfo(false);
            valve.setShowReport(false);
            valve.setAsyncSupported(true);
            context.getParent().getPipeline().addValve(valve);
        });
    }
}
